//
//  WmcFeedbackInputCell.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/1.
//

import UIKit
import YPBedrock

// MARK: - [WmcFeedbackInputCell]

class WmcFeedbackInputCell: WmcBaseTableCell {
    // Internal

    var textDidChange: ((String?) -> Void)?

    var imagesDidChange: (([UIImage]) -> Void)?

    var clickImage: ((Int) -> Void)?

    lazy var textView: UITextView = {
        let textView = UITextView()
        textView.contentInset = .zero
        textView.textContainerInset = .zero
        textView.font = 17.wmc_font
        textView.returnKeyType = .done
        textView.delegate = self
        textView.isScrollEnabled = true
        return textView
    }()

    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout
            .YP.CreateGridLayout(scrollDirection: .vertical,
                                 minimumLineSpacing: 0,
                                 minimumInteritemSpacing: 0,
                                 sectionInset: Wmc_standardEdge)
        return layout
    }()

    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView
            .YP.Create(layout: layout,
                       delegate: self,
                       dataSource: self,
                       registers: [
                           YPRegister(WmcFeedbackInputCellImageCell.self),
                       ])
        collectionView.isScrollEnabled = false
        return collectionView
    }()

    lazy var textCountLabel: UILabel = {
        let label = UILabel.YP.Create(text: "0/200",
                                      font: 12,
                                      color: UIColor.wmc_grayH8_8A8A99,
                                      alignment: .right)
        return label
    }()

    /// 用于更新高度
    weak var tableView: UITableView?
    /// 用于更新高度
    var indexPath: IndexPath?
    /// 用于更新高度
    var beforeTextHeight: CGFloat = 0

    lazy var images: [WmcFeedbackImageModel] = {
        let item_1 = WmcFeedbackImageModel()
        item_1.style = .add

        let item_2 = WmcFeedbackImageModel()
        item_2.style = .none

        let item_3 = WmcFeedbackImageModel()
        item_3.style = .none

        return [item_1, item_2, item_3]
    }()

    var surplusImgsCount: Int {
        var count = 0
        images.forEach { model in
            if model.style == .image {
                count += 1
            }
        }
        var surplus = 3 - count
        if surplus < 0 {
            surplus = 0
        }
        return surplus
    }

    override func makeUI() {
        addSubview(textView)
        textView.snp.makeConstraints { make in
            make.top.equalTo(Wmc_standardEdge.top)
            make.left.equalTo(Wmc_standardEdge.left - 4)
            make.right.equalTo(-Wmc_standardEdge.right)
            make.height.greaterThanOrEqualTo(84)
        }

        titleLabel.textColor = .wmc_grayH8_8A8A99
        titleLabel.font = 17.wmc_font
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(Wmc_standardEdge.top)
            make.left.equalTo(Wmc_standardEdge.left)
            make.height.equalTo(20)
        }

        addSubview(textCountLabel)
        textCountLabel.snp.makeConstraints { make in
            make.right.equalTo(-Wmc_standardEdge.right)
            make.bottom.equalTo(-Wmc_standardEdge.bottom)
            make.height.equalTo(15)
            make.width.equalTo(50)
        }

        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(textView.snp.bottom)
            make.left.bottom.equalToSuperview()
            make.right.equalTo(textCountLabel.snp.left)
            make.height.greaterThanOrEqualTo(110.wmc_autoHor)
        }
    }

    func configModel(_ model: WmcFeedbackVM.CellModel) {
        guard model.style == .input else { return }
        titleLabel.text = model.title
    }

    // Private

    override func bindEvent() {
        textView.rx.didChange.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.textDidChange?(weakSelf.textView.text)
        }).disposed(by: rx.disposeBag)
    }

    private func appendImages(_ images: [UIImage]) {
        if images.count > surplusImgsCount {
            WmcLogManager.Log("选择图片出错")
            return
        }

        var temp: [WmcFeedbackImageModel] = []
        var i = 0
        var isAdd = false
        for (_, item) in self.images.enumerated() {
            if item.style == .image {
                temp.append(item)
            } else {
                if i < images.count {
                    let model = WmcFeedbackImageModel()
                    model.image = images[i]
                    model.style = .image
                    temp.append(model)
                    i += 1
                } else {
                    if isAdd {
                        let model = WmcFeedbackImageModel()
                        model.style = .none
                        temp.append(model)
                    } else {
                        let model = WmcFeedbackImageModel()
                        model.style = .add
                        temp.append(model)
                        isAdd = true
                    }
                }
            }
        }
        self.images = temp
        selcetImages()
        collectionView.reloadData()
    }

    private func delImage(index: Int) {
        var temp: [WmcFeedbackImageModel] = images
        if index < temp.count {
            temp.remove(at: index)
        }

        var imgs: [WmcFeedbackImageModel] = []
        temp.forEach { model in
            if model.style == .image {
                imgs.append(model)
            }
        }
        temp = imgs
        var isAdd = false
        var result: [WmcFeedbackImageModel] = []
        for i in 0 ..< 3 {
            if i < temp.count {
                result.append(temp[i])
            } else {
                if isAdd {
                    let model = WmcFeedbackImageModel()
                    model.style = .none
                    result.append(model)
                } else {
                    let model = WmcFeedbackImageModel()
                    model.style = .add
                    result.append(model)
                    isAdd = true
                }
            }
        }
        self.images = result
        selcetImages()
        collectionView.reloadData()
    }

    private func selcetImages() {
        var result: [UIImage] = []
        self.images.forEach { model in
            if model.style == .image, let img = model.image {
                result.append(img)
            }
        }
        imagesDidChange?(result)
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate

extension WmcFeedbackInputCell: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        picker.dismiss(animated: true, completion: nil)
        let key = UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerOriginalImage")
        guard let image = info[key] as? UIImage else { return }
        appendImages([image])
    }
}

// MARK: - UICollectionViewDelegate

extension WmcFeedbackInputCell: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let _ = images.yp.object(at: indexPath.row) else { return }
        clickImage?(indexPath.row)
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension WmcFeedbackInputCell: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height = collectionView.frame.height - self.layout.sectionInset.yp.vertical
        return CGSize(width: height + 6, height: height + 6)
    }
}

// MARK: - UICollectionViewDataSource

extension WmcFeedbackInputCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: WmcFeedbackInputCellImageCell = collectionView.yp.dequeueReusableCell(for: indexPath)
        if let model = images.yp.object(at: indexPath.row) {
            cell.configModel(model, indexPath: indexPath)
        }

        cell.addClosure = { model in
            self.showSelectPhoto()
        }

        cell.delClosure = { (model, indexPath) in
            self.delImage(index: indexPath.row)
        }
        return cell
    }

    private func showSelectPhoto() {
        let sheet = WmcSheetView()
        sheet.title = "上传照片"
        sheet.items = ["拍照", "相册"]
        sheet.show(height: 250)
        sheet.didSelectIndexBlock = { [weak self] index in
            guard let weakSelf = self else { return }
            switch index {
            case 0:
                let cameraStatus = WmcAuthorizedManager.camera()
                if cameraStatus.info.isAvailable {
                    weakSelf.takePhoto()
                } else {
                    WmcAuthorizedManager.showCameraPermissionAlert()
                }
            case 1:
                let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                if photoAlbumStatus.info.isAvailable {
                    weakSelf.selectPhoto()
                } else {
                    WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                }
            default: break
            }
        }
    }

    private func takePhoto() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        YPApp.CurrentVC?.present(imagePicker, animated: true, completion: nil)
    }

    private func selectPhoto() {
        guard surplusImgsCount > 0 else { return }

        WmcPhotoSelectManager.photoSelect(vc: YPApp.CurrentVC, maxCount: surplusImgsCount) { [weak self] imgs in
            guard let weakSelf = self else { return }
            weakSelf.appendImages(imgs)
        }
    }
}

// MARK: - UITextViewDelegate

extension WmcFeedbackInputCell: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        guard var text = textView.text else { return }
        text = text.yp.replacing("\n", with: "")
        if text.count > 200 {
            text = text.yp.keepPrefix(count: 200)
            textView.text = text
        }
        titleLabel.isHidden = textView.text.count > 0
        textCountLabel.text = "\(textView.text.count)/200"

        var height = textView.sizeThatFits(CGSize(width: textView.yp.width, height: .greatestFiniteMagnitude)).height
        guard beforeTextHeight != height else { return }
        if height < 84 {
            height = 84
        }
        beforeTextHeight = height
        textView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(height)
        }
        tableView?.beginUpdates()
        tableView?.endUpdates()
    }

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            textView.resignFirstResponder()
            return false
        }
        return true
    }
}
